package com.ebelter.temperature.activitys;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.bases.activity.BaseHandleActivity;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.common.IOrder;
import com.ebelter.btcomlib.models.bluetooth.base.BlueManager;
import com.ebelter.btcomlib.models.bluetooth.base.BlueScan;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IBlueStationListener;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScanCallback;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.TemperatureConstant;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.TemperatureManager;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.bean.DateTime;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.bean.TMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.interfaces.I_T_MeasureCallback;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.GetTempertureData2;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.ChartView2;
import com.ebelter.temperature.R;
import com.ebelter.temperature.adapters.TBandDeviceAdapter;
import com.ebelter.temperature.models.T_UploadUtil;
import com.ebelter.temperature.models.T_WarringModelUtils;
import com.ebelter.temperature.view.CombinView2;
import com.ebelter.temperature.view.CombinView3;

import java.util.ArrayList;

import java.util.List;




public class T_MainActivity extends BaseHandleActivity implements IOrder {

    public static final String TAG="T_MainActivity";

    private static final int WHAT_CHECK_HEART = 2;//检测心跳
    private static final int WHAT_cb2_animation_resume = 3;//恢复小圆点旋转

    LinearLayout nopairedtiply_root_ll;
    TextView top_name_tv;
    CombinView2 main_cb2;
    ChartView2 chartview2;

    CombinView3 m_first_cb3;
    CombinView3 m_tow_cb3;

    ImageView main_redbg_iv;
    ImageView main_red_iv;

    private TemperatureManager mTemperatureManager;
    private BlueScan mBlueScan;

    private T_UploadUtil mT_UploadUtil;
    private T_WarringModelUtils mT_WarringModelUtils;


    @Override
    protected void handleMsg(Message msg) {
      if(msg.what==WHAT_CHECK_HEART){//检测心跳包

          removeMessages(WHAT_CHECK_HEART);
            sendEmptyMessageDelayed(WHAT_CHECK_HEART,5000);
            checkHeart();
      }else if (msg.what == WHAT_cb2_animation_resume){
          cb2_animation_resume();
      }

    }

    //检测心跳包
    private void checkHeart() {

        LogUtils.i(TAG,"----------------checkHeart()");

        if (mTemperatureManager==null)return;

        if (mTemperatureManager.isBondDevice()){
            ViewUtils.hideView(nopairedtiply_root_ll);

            if (mTemperatureManager.isConnect()){
                LogUtils.i(TAG,"----------------checkHeart()--连接中");
            }else {
                LogUtils.i(TAG,"----------------checkHeart()--未连接--准备连接");
                mTemperatureManager.connectDevice(mTemperatureManager.getBondDeviceAddress());
            }

        }else {
            LogUtils.i(TAG,"----------------checkHeart()--设备没有绑定");
            ViewUtils.displayView(nopairedtiply_root_ll);

        }





    }

    //开始扫描设备
    private void startScan(){
        LogUtils.i(TAG,"开始扫描设备--startScan（）");
        if (mBlueScan!=null) mBlueScan.startScanBluetoothDevices();
    }

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_t_main;
    }

    @Override
    protected void initView() {
        StatusBarUtil.setColor(this, Color.parseColor("#787ede"));
        FV();

      //  main_cb2.animation_start();
        main_cb2.animation_start();
        main_cb2.animation_pause();

        boolean isOpenWarring=UserSpUtil.readBoolean(Constants.IUser.T_Warring_isOpen,true);
        if (isOpenWarring){
            ViewUtils.displayView(main_red_iv);
        }else {
            ViewUtils.hideView(main_red_iv);
        }
        if (main_redbg_iv!=null) main_redbg_iv.setImageResource(isOpenWarring?R.drawable.ic_swake:R.drawable.ic_swake2);
        setWarringModel(isOpenWarring);

        ViewUtils.setTextViewStr(top_name_tv,UserSpUtil.readString(Constants.IUser.NICK_NAME));

    }


    private void displayWarringTemperature(){
        float warringTemperature = UserSpUtil.readFloat(Constants.IUser.T_Warring_Value,38);
        if(main_cb2!=null)main_cb2.setWarring_tv_tv(warringTemperature+" ℃");
        if(chartview2!=null)chartview2.warringTem = warringTemperature;
    }



    private void cb2_animation_pause(){
        if (main_cb2!=null)main_cb2.animation_pause();
    }

    private void cb2_animation_resume(){
        if (main_cb2!=null)main_cb2.animation_resume();
    }


    private IBlueStationListener mIBlueStationListener;


    private void setListener() {

        mT_UploadUtil=new T_UploadUtil(this,this);

        mT_UploadUtil.startCheckDB();//开始检测缓存数据库

        mBlueScan.setScanCallback(new IScanCallback() {
            @Override
            public void beforeScan() {}

            @Override
            public void scanOneDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
                LogUtils.i(TAG,"扫描到设备：name="+device.getName()+"---address="+device.getAddress());
                if (!TextUtils.equals(device.getName(), TemperatureConstant.T_NAME)){
                    return;
                }
                if (mTemperatureManager!=null){
                    mTemperatureManager.connectDevice(device.getAddress());
                }
            }

            @Override
            public void overScan() {}
        });

        mTemperatureManager.setBlueConnectStationCallback(new IConnectStationCallback() {
            @Override
            public void onConnected(ProductStyle productStyle,BluetoothDevice device) {
                LogUtils.i(TAG,"----------onConnected");
                mTemperatureManager.syncSystemClock();
                if(main_cb2!=null){
                    main_cb2.animation_resume();
                }
            }

            @Override
            public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {

            }

            @Override
            public void onDisConnected(ProductStyle productStyle) {
                cb2_animation_pause();//让选转圈暂停
                LogUtils.i(TAG,"----------onDisConnected");
            }
        });

        mTemperatureManager.setmIMeasureResultCallback(new I_T_MeasureCallback() {
            @Override
            public void timeOutOfSync() {
                LogUtils.i(TAG,"IMeasureResultCallback-接收到时间未同步信息");
                mTemperatureManager.syncSystemClock();
            }

            @Override
            public void deviceTime(DateTime deviceTime) {
                LogUtils.i(TAG,"IMeasureResultCallback-接收到设备时间信息---"+deviceTime.toString());
                mTemperatureManager.getHistory();
            }

            @Override
            public void noHistoryData() {
                LogUtils.i(TAG,"IMeasureResultCallback-接收到---noHistoryData");
            }

            @Override
            public void clearAllHistoryDataFinish() {
                LogUtils.i(TAG,"IMeasureResultCallback-接收到---clearAllHistoryDataFinish");
            }

            @Override
            public void temperture(int temperture) {
                LogUtils.i(TAG,"IMeasureResultCallback-接收到---temperture = "+temperture);
                receiverTemperture(temperture);
            }
        });


        mIBlueStationListener=new IBlueStationListener() {
            @Override
            public void STATE_OFF() {
                if (mTemperatureManager!=null){
                    mTemperatureManager.openBluetooth2(T_MainActivity.this,10);
                }
            }

            @Override
            public void STATE_TURNING_OFF() {

            }

            @Override
            public void STATE_ON() {

            }

            @Override
            public void STATE_TURNING_ON() {

            }
        };
        BlueManager.getInstance().addBluetoothStationListener(mIBlueStationListener);

    }

    //接收到实时的温度
    private void receiverTemperture(int temperture) {

    //    cb2_animation_pause();//让选转圈暂停
//        removeMessages(WHAT_cb2_animation_resume);//3秒后让圈继续旋转
//        sendEmptyMessageDelayed(WHAT_cb2_animation_resume,3000);

        displayTemperture(temperture);
    }

    //显示温度
    private void displayTemperture(int temperture){
        if (main_cb2!=null){

            float displayTem= NumUtils.numBaoLiuWei1((float) (temperture*1.0/100));

            main_cb2.setTemperature_tv(displayTem+"℃");

            mT_WarringModelUtils.receiveTemperature(displayTem);//提示模式 响铃或者震动

            //cb显示接收的时间
            long t=System.currentTimeMillis();
            String disTime=TimeUtils.formatDateStampString1(this,t)+" "+TimeUtils.formatDateStampString2(this,t);
            main_cb2.setDate_tv(disTime);

            String upLoadTime = TimeUtils.formatTime1(t);

            if (chartview2!=null){//往表格里添加一条数据
                chartview2.addXValue(upLoadTime,displayTem);
            }

            if (t-lastUploadDataTime<300000){
                LogUtils.i(TAG,"距离上一次上传时间相差没有5分钟,此次数据屏蔽掉了");
                return;
            }



            long userid = UserSpUtil.readLong(Constants.IUser.USER_ID,-1);
            if (userid<=0){
                LogUtils.i(TAG,"未登录状态 不上传数据");
                return;//未登录状态就不用上传了
            }

            lastUploadDataTime = t;

            TMesureResult tMesureResult = new TMesureResult();
            tMesureResult.userID = userid;
            tMesureResult.mesureValue = displayTem;
            tMesureResult.testTime = upLoadTime;

            if (mT_UploadUtil!=null){
                mT_UploadUtil.upload(this,tMesureResult);
            }


        }
    }


    public void adddd(){
        TMesureResult tMesureResult = new TMesureResult();
        long userid = UserSpUtil.readLong(Constants.IUser.USER_ID,-1);
        if (userid<=0){
            LogUtils.i(TAG,"未登录状态 不上传数据");
            return;//未登录状态就不用上传了
        }
        tMesureResult.userID = userid;
        tMesureResult.mesureValue = 29.5f;
        tMesureResult.testTime = "2019-01-07 12:12:12";

        if (mT_UploadUtil!=null){
            mT_UploadUtil.upload(this,tMesureResult);
        }
    }

    private long lastUploadDataTime;


    @Override
    protected void initData() {




        mTemperatureManager = new TemperatureManager(this);

        mTemperatureManager.openBluetooth2(this,10);




        mT_WarringModelUtils=new T_WarringModelUtils(getApplicationContext());
        mBlueScan = new BlueScan(this);

        setListener();
        initCharView();
       // getTodayData();
        get2HData();


    }

    //初始化charView
    private void initCharView() {
        //y轴坐标对应的数据
        List<Float> oneYValue = new ArrayList<>();
        for (int i = 0; i < 4; i++) {//Y轴的刻度值
            oneYValue.add(i *15f);
        }
        chartview2.isDisplayXDateFlag = false;
        chartview2.setYValue(oneYValue);
    }

    private void FV() {
        nopairedtiply_root_ll=findViewById(R.id.nopairedtiply_root_ll);
        top_name_tv=findViewById(R.id.top_name_tv);
        main_red_iv=findViewById(R.id.main_red_iv);//小红点
        main_redbg_iv=findViewById(R.id.main_redbg_iv);
        main_cb2=findViewById(R.id.main_cb2);
        chartview2=findViewById(R.id.chartview2);
        m_first_cb3 = findViewById(R.id.m_first_cb3);
        m_tow_cb3 = findViewById(R.id.m_tow_cb3);
    }

    @Override
    protected void onResume() {
        super.onResume();
       // checkBandDevice();
        removeMessages(WHAT_CHECK_HEART);
        sendEmptyMessage(WHAT_CHECK_HEART);
        displayWarringTemperature();//显示警告温度
    }

    @Override
    protected void onPause() {
        super.onPause();
        removeMessages(WHAT_CHECK_HEART);
    }



    //设置
    public void setteing(View view) {
        startActivity(T_SettingActivity.class);
    }


    //历史列表
    public void historyClick(View view){
        LogUtils.i(TAG,"历史页面");
        startActivity(T_HistoryActivity.class);
    }

    //绑定页面
    public void bondDeviceClick(View view){
        LogUtils.i(TAG,"绑定页面");
        Intent intent=new Intent(this, T_BandDeviceActivity.class);
        startActivityForResult(intent,T_BandDeviceActivity.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==T_BandDeviceActivity.REQUEST_CODE){
            removeMessages(WHAT_CHECK_HEART);
            sendEmptyMessage(WHAT_CHECK_HEART);
        }


    }

    @Override
    public void cmd(int cmd, Object... objects) {
//        if (cmd==T_UploadUtil.UPLOAD_DATA_SUCCESS){
//            //说明有一条数据上传成功了
//            //getTodayData();
//        }
    }

    @Override
    protected boolean isOpenNetStationListener() {
        return true;
    }

    @Override
    protected void netStationChange(int netWorkState) {
        LogUtils.i(TAG,"接收到网络状态监听器--netWorkState = " + netWorkState);


//        }
    }


    @Override
    public boolean isOpenTimeChangeListener() {
        return true;
    }

    @Override
    protected void timeChange(int which) {
        LogUtils.i(TAG,"接收到时间状态监听器--which = " + which);
        get2HData();
    }




    //获取2个小时的数据
    private void get2HData() {
       String testDate = TimeUtils.getCurrentTime1();
       // String testDate = "2018-07-04 14:43:23";
        LogUtils.i(TAG,"------------get2HData()--testDate = "+testDate);


        NetUtils.getInstance().getData_T(this, testDate, new HttpResponse<GetTempertureData2>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetTempertureData2 getTempertureData2, String s) {
                LogUtils.i(TAG,"------get2HData----- s = " + s);
                if (!isRequestSuccess){
                    return;
                }
                LogUtils.i(TAG,"----get2HData---" + getTempertureData2.toString());
                if (getTempertureData2.getResultCode()==0){//说明请求成功
                    // disCharView(getTempertureData);
                    LogUtils.i(TAG,"----------- getTempertureData2 = "+getTempertureData2.toString());
                    disPlay2Hour(getTempertureData2);
                }
            }
        });


    }


    //显示2个小时的控件
    private void disPlay2Hour(GetTempertureData2 getTempertureData2) {

        if (getTempertureData2.getResultData()==null||getTempertureData2.getResultData().size()==0){
            return;
        }

        List<GetTempertureData2.ResultDataBean> dataBeans = getTempertureData2.getResultData();
        GetTempertureData2.ResultDataBean first = dataBeans.get(0);
        GetTempertureData2.ResultDataBean last = null;
        if (dataBeans.size()>1){
            last=dataBeans.get(1);
        }



        if (m_first_cb3!=null&&first!=null&&first.getDataTemperature()!=null){
            m_first_cb3.setTitle1Str(first.getDataTemperature().getTemperature()+" ℃",false);
            long ts=TimeUtils.parseFormatter1Time(first.getDataTemperature().getTestDate()).getTime();
            String time=TimeUtils.formatDateStampString1(CommonLib.APPContext,ts)+" "+TimeUtils.formatDateStampString2(CommonLib.APPContext,ts);
            m_first_cb3.setTitle2Str(time,false);
            m_first_cb3.setTitle3Str(first.getValue()+" ℃",false);
            //控件 0lose 1nochange 2add
            //后台0:没有对比;1:上升;2:下降 3没有变化的返回
            int station=-1;
            if (first.getTendency()==0){
                station=-1;
            }else if (first.getTendency()==1){
                station=2;
            }else if (first.getTendency()==2){
                station=0;
            }else if (first.getTendency()==3){
                station=1;
            }
            m_first_cb3.setStation(station,true);
        }

        if (m_tow_cb3!=null){

            if (last!=null&&last.getDataTemperature()!=null){
                m_tow_cb3.setTitle1Str(last.getDataTemperature().getTemperature()+" ℃",false);
                long ts=TimeUtils.parseFormatter1Time(last.getDataTemperature().getTestDate()).getTime();

                String time=TimeUtils.formatDateStampString1(CommonLib.APPContext,ts)+" "+TimeUtils.formatDateStampString2(CommonLib.APPContext,ts);
                m_tow_cb3.setTitle2Str(time,false);
                m_tow_cb3.setTitle3Str(last.getValue()+" ℃",false);
                //控件 0lose 1nochange 2add
                //后台0:没有对比;1:上升;2:下降 3没有变化的返回
                int station=-1;
                if (last.getTendency()==0){
                    station=-1;
                }else if (last.getTendency()==1){
                    station=2;
                }else if (last.getTendency()==2){
                    station=0;
                }else if (last.getTendency()==3){
                    station=1;
                }
                m_tow_cb3.setStation(station,true);
            }else{
                m_tow_cb3.setTitle1Str("-- ℃",false);
                m_tow_cb3.setTitle2Str("---- --:--",false);
                m_tow_cb3.setTitle3Str("--",false);
                m_tow_cb3.setStation(-1,true);
            }

        }


    }


    //显示数据到表格控件上
//    private void disCharView(GetTempertureData tempertureData) {
//        if (tempertureData==null||tempertureData.getResultData()==null||tempertureData.getResultData().getData()==null||tempertureData.getResultData().getData().size()==0){
//            return;
//        }
//
//
//        //x轴坐标对应的数据
//        List<String> oneXValue = new ArrayList<>();
//
//        //y轴坐标对应的数据
//        List<Float> oneYValue = new ArrayList<>();
//        for (int i = 0; i < 4; i++) {//Y轴的刻度值
//            oneYValue.add(i *15f);
//        }
//
//        //折线对应的数据
//        Map<String, Float> oneValue = new HashMap<>();
//
//
//
//        List<GetTempertureData.ResultDataBean.DataBean> datas = tempertureData.getResultData().getData();
//
//
//
//        for (int i=0;i<datas.size();i++){
//            GetTempertureData.ResultDataBean.DataBean bean = datas.get(i);
//            String testTime = bean.getTestDate();
//
//            oneXValue.add(testTime);
//            oneValue.put(testTime, NumUtils.numBaoLiuWei1(bean.getTemperature()));
//        }
//
//
//
//        if (chartview2!=null){
//            chartview2.isDisplayXDateFlag = false;
//            chartview2.setValue(oneValue,oneXValue,oneYValue);
//        }
//
//
//
//
//
//
//
//    }


    private long firstBackTime;
    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstBackTime > 2000) {
            ToastUtil.show(R.string.Touch_again_to_exit);
            firstBackTime = secondTime;
        } else {
            System.exit(0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mT_UploadUtil!=null)mT_UploadUtil.exit();
        mT_UploadUtil=null;
        BlueManager.getInstance().removeBluetoothStationListener(mIBlueStationListener);
        mIBlueStationListener=null;
    }


    //小红点被点击
    public void main_red_iv_click(View view) {
      //  adddd();
        boolean isOpenWarring = UserSpUtil.readBoolean(Constants.IUser.T_Warring_isOpen,true);
        if (isOpenWarring){//打开--->关闭
            UserSpUtil.writeBoolean(Constants.IUser.T_Warring_isOpen,false);
            ViewUtils.hideView(main_red_iv);
            ToastUtil.show("高温警报铃已关闭");
        }else {//关闭--->打开
            UserSpUtil.writeBoolean(Constants.IUser.T_Warring_isOpen,true);
            ViewUtils.displayView(main_red_iv);
            ToastUtil.show("高温警报铃已开启");
        }
        if (main_redbg_iv!=null) {main_redbg_iv.setImageResource(isOpenWarring?R.drawable.ic_swake2:R.drawable.ic_swake);}
        setWarringModel(!isOpenWarring);

    }


    private void setWarringModel(boolean isOpen){
        if (mT_WarringModelUtils!=null){
            mT_WarringModelUtils.setOpen(isOpen);
        }
    }

}
